<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 14-6-8
 * Time: 下午7:55
 */

namespace Macaca\Module\Admin;

use Library\Verification;
use Macaca;
use Monkey;

class User {

    /**
     * @var Monkey\App
     */
    public $app;

    private $modelUser;
    public $modelPriKey;
    public $modelNameKey;
    private $modelCacheKey = 'MacacaUser';

    /**
     * @param Monkey\App $app
     */
    public function __construct($app) {
        $this->app = $app;
        $_SESSION['user']['last_url'] = $app->request()->getUri();
        $this->modelUser = new Macaca\Model\Admin\User($this->app);
        $this->modelPriKey = $this->modelUser->priKey;
        $this->modelNameKey = $this->modelUser->nameKey;
    }

    public function getUserByName($name) {
        $result = array();
        $cache = $this->app->cache();
        if (!$cache->fetch($this->modelCacheKey . $name, $result)) {
            $result = $this->modelUser->find($this->modelNameKey, $name);
            $cache->store($this->modelCacheKey . $name, $result);
        }
//        $result = $this->modelUser->find($this->modelNameKey, $name);
        return $result;
    }

    public function login($data) {
        $user = array();
        $nk = $this->modelNameKey;
        //规则验证
        $verification = new Verification();
        if (!isset($data[$nk]) or !$verification->isUserName($data[$nk])) {
            return false;
        }
        if (!isset($data['password']) or !$verification->isSafeAll($data['password'])) {
            return false;
        }
        //数据库验证
        $mUser = $this->getUserByName($data[$nk]);
        if (empty($mUser)) {
            return false;
        }
        if ($this->createPassword($data['password'], $data[$nk]) != $mUser['password']) {
            return false;
        }
        //记录日志
        $user[$this->modelPriKey] = $mUser[$this->modelPriKey];
        $user[$nk] = $data[$nk];
        $user['password'] = $data['password'];
        $user['last_ip'] = $this->app->request()->getIP();
        $user['last_time'] = $this->app->TIME;
        $mUser['last_ip'] = isset($user['last_ip']) ? $user['last_ip'] : '';
        $mUser['last_time'] = isset($user['last_time']) ? $user['last_time'] : '';

        if (!$this->modelUser->updateByPriKey($mUser[$this->modelPriKey], $mUser)) {
            return false;
        }
        $_SESSION['user'] += $user;
        return true;
    }

    public function logout() {
        //仅仅删除登录数据，保留其它操作数据
        $_SESSION['user'] = null;
        //下面是注销当前SessionID的所有Session数据
        //session_destroy();
    }

    /**
     * 检测用户是否登录
     * @return bool
     */
    public function checkLogin() {
        if (!isset($_SESSION['user']) or !isset($_SESSION['user']['last_ip'])) {
            return false;
        }
        if ($this->app->request()->getIP() != $_SESSION['user']['last_ip']) {
            return false;
        }
        if ($_SESSION['user']['last_time'] + 200 * 60 * 1000 < $this->app->TIME) {
            return false;
        } //页面操作时间间隔长于20分钟视为超时
        $_SESSION['user']['last_time'] = $this->app->TIME; //更新活跃时间
        return true;
    }

    public function getFieldFromSession($field) {
        if (isset($_SESSION['user']) and isset($_SESSION['user'][$field])) {
            return $_SESSION['user'][$field];
        }
        else {
            return null;
        }
    }

    protected function createPassword($src, $uname) {
        return md5($src);
        //        return md5($uname.$src.'Macaca');
    }

    /**
     * @return int
     */
    public function getCount() {
        $result = 0;
        $cache = $this->app->cache();
        if (!$cache->fetch($this->modelCacheKey . 'count', $result)) {
            $result = $this->modelUser->count();
            $cache->store($this->modelCacheKey . 'count', $result);
        }
        return $result;
    }

    /**
     * @param int $page
     * @param int $pageLength
     *
     * @return array  //$uid,$uname,$password,$email,$last_ip,$last_time
     */
    public function getUserList($page = 0, $pageLength = 10) {
        return $this->modelUser->findList($page, $pageLength);
    }

    /**
     * 获取一个空页面 //$uid,$uname,$password,$email,$last_ip,$last_time
     * @return mixed
     */
    public function getEmptyItem() {
        $data['uid'] = '';
        $data['uname'] = '';
        $data['email'] = '';
        $data['last_ip'] = '';
        $data['last_time'] = 0;
        return $data;
    }

    public function getItemById($uId) {
        $data = $this->modelUser->find($this->modelPriKey, $uId);

        if ($data) {
            return $data;
        }
        else {
            return array();
        }
    }

    public function deleteItemById($uId) {
        if ($this->modelUser->delete($this->modelPriKey, $uId)) {
            $this->resetCache();
            return true;
        }
        else {
            return false;
        }
    }

    public function saveItem($data = array()) {
        $pk = $this->modelPriKey;
        if (!empty($data[$pk]) and !is_numeric($data[$pk])) {
            return false;
        }

        $dataTemp = $this->getEmptyItem();
        unset($dataTemp[$pk]);
        foreach ($dataTemp as $k => $v) {
            if (!isset($data[$k])) {
                return false;
            }
            $dataTemp[$k] = $data[$k];
        }

        if (!empty($data[$pk])) {
            if (isset($data['password'])) {
                $dataTemp['password'] = $this->createPassword($data['password'], $data['uname']);
            }
            $result = $this->modelUser->updateByPriKey($data[$pk], $dataTemp);
            $this->app->cache()->delete($this->modelCacheKey . $dataTemp[$this->modelNameKey]);
        }
        else {
            empty($data['password']) and $data['password'] = '88888888';
            $dataTemp['password'] = $this->createPassword($data['password'], $data['uname']);
            $result = $this->modelUser->insert($dataTemp);
        }

        if ($result) {
            $this->resetCache();
        }

        return $result;
    }

    protected function resetCache() {
        $this->app->cache()->delete($this->modelCacheKey . 'count');
    }
} 